<?php
/**
 * 持仓时长敞口风控脚本：
 *   BTC 20x杠杆 持仓时间不能超过5分钟；
 *   BTC 10x杠杆 持仓时间不能超过15分钟；
 *   BTC 3x杠杆  持仓时间不能超过1小时；
 *   BTC 1x杠杆  持仓时间不能超过4小时；
 * 依据：
 *   海龟法则。总资产日亏损不可超过1%。
 */

use Www\Wss\BinanceFuturesAPI;
require __DIR__.'/../vendor/autoload.php';
$api = new BinanceFuturesAPI(__DIR__.'/../.config/my-binance-acc-1.json');

/**
 * 自动设置止盈止损（一般风控程序）
 */
function global_risk_ctrl($api, $symbol)
{
	static $lastCallTime=0;
	if($lastCallTime > 0 && time()-$lastCallTime < 5){
		echo "Last-Call-Time ignore in 5 seconds.\n";
		return false;
	}
	$lastCallTime = time();
    $riskUrl = $api->risk_url.'&op=global_risk_ctrl';
    echo file_get_contents($riskUrl),PHP_EOL;
    echo $symbol.' SL-TP is set.',PHP_EOL;
}

//余额或仓位变动回调函数
$balance_update = function($api, $balances) {
	echo "Balance or Position update".PHP_EOL;
	// print_r($balances);
    // list($balances, $positions) = $balances;
    if(!empty($balances[1])){
		global_risk_ctrl($api, implode(',',array_keys($balances[1]))); //不管是新开仓还是新平仓：都调用风控！
        // foreach($balances[1] as $symbol => $pos){
        //     if($pos['quanlity'] != 0) {
        //         auto_place_sl_tp($api, $symbol);
        //     }
        // }
    }
    echo PHP_EOL;
};

//订单变动回调函数
$order_update = function($api, $report) {
	echo "Order update".PHP_EOL;
	// print_r($report);
	$price = $report['price'];
	$quantity = $report['quantity'];
	$symbol = $report['symbol'];
	$side = $report['side'];
	$orderType = $report['orderType'];
	$orderId = $report['orderId'];
	$orderStatus = $report['orderStatus'];
	$executionType = $report['executionType'];
	// if ( $executionType == "NEW" ) {
	// 	if ( $orderStatus == "REJECTED" ) {
	// 		echo "Order Failed! Reason: {$report['rejectReason']}".PHP_EOL;
	// 	}
	// 	echo "{$symbol} {$side} {$orderType} ORDER #{$orderId} ({$orderStatus})".PHP_EOL;
	// 	echo "..price: {$price}, quantity: {$quantity}".PHP_EOL;
	// 	return;
	// }
	//NEW, CANCELED, REPLACED, REJECTED, TRADE, EXPIRED
	echo "{$symbol} {$side} {$executionType} {$orderType} ORDER #{$orderId}".PHP_EOL;
    echo PHP_EOL;
};

//主函数：
$api->userData($balance_update, $order_update);


/* 
Order update
GRASSUSDT SELL NEW LIMIT ORDER #92831337

Balance or Position update
{"errcode":0,"errmsg":"ok"}冷静期中...cool down period!
GRASSUSDT SL-TP is set.

Order update
GRASSUSDT SELL TRADE LIMIT ORDER #92831337

Order update
GRASSUSDT BUY NEW MARKET ORDER #92831474

Balance or Position update
Last-Call-Time ignore in 5 seconds.

Order update
GRASSUSDT BUY TRADE MARKET ORDER #92831474
 */
